package com.xsomnus.rpc.consumer.config.rpc;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Proxy;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019/4/22 0022 18:02
 * 当你发现自己的才华撑不起野心时，就请安静下来学习吧
 */
public class RPCFactoryBean<T> implements FactoryBean<T> {

    private Class<T> rpcInterface;

    @Autowired
    RPCFactory<T> factory;

    public RPCFactoryBean() {}

    public RPCFactoryBean(Class<T> rpcInterface) {
        this.rpcInterface = rpcInterface;
    }


    @Override
    public T getObject() throws Exception {
        return getRpc();
    }

    @Override
    public Class<?> getObjectType() {
        return this.rpcInterface;
    }

    /**
     * 创建RPC接口的代理对象, 而在代理对象中, 实际上是使用远程调用的实现
     * 基于JDK实现
     */
    @SuppressWarnings("unchecked")
    public T getRpc() {
        return (T) Proxy.newProxyInstance(rpcInterface.getClassLoader(), new Class[]{ rpcInterface }, factory);
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
